import pandas as pd
import datetime
import shutil
import json
import os
import re


# 获得图幅列表
def get_tiles(province, json_path=None):
	""""""
	if json_path is None:
		json_path = r"/home/冯洋洋/PythonProjection/RasterShape/conf/ChinaMgrs.json"
	with open(json_path, "r", encoding="UTF-8") as jsonFile:
		provinceMgrsd = json.load(jsonFile)
	return provinceMgrsd[province]


# 获取日期列表
def get_dates(start_date, end_date):
	""""""
	year, month, day = start_date
	start_date = datetime.datetime(year, month, day)
	year, month, day = end_date
	end_date = datetime.datetime(year, month, day)
	dates = []
	while start_date < end_date:
		dates.append(start_date)
		start_date += datetime.timedelta(days=+1)
	return dates


# 获得 l1c zip各个文件数量
def get_l1c_zip_count_xlsx(
		tiles, dates, zip_folder_paths, xlsx_path):
	""""""
	dates = [date.strftime("%Y%m%d") for date in dates]
	zip_count_dataframe = pd.DataFrame(columns=dates, index=tiles)
	for tile in tiles:
		for date in dates:
			zip_file_name_re = f"^S2[AB]_MSIL1C_{date}T.*_T{tile}_.*\.zip$"
			zip_file_names = [
				file_name
				for zip_folder_path in zip_folder_paths
				for file_name in os.listdir(zip_folder_path)
				if re.match(zip_file_name_re, file_name)
			]
			file_count = len(set(zip_file_names))
			if file_count != 0:
				zip_count_dataframe[date][tile] = file_count
	sheet_name = datetime.datetime.now().strftime('%Y%m%d_%H-%M-%S')
	if os.path.exists(xlsx_path):
		with pd.ExcelWriter(xlsx_path, mode="a", engine='openpyxl') as writer:
			zip_count_dataframe.to_excel(writer, sheet_name=sheet_name)
	else:
		with pd.ExcelWriter(xlsx_path, mode="w", engine='openpyxl') as writer:
			zip_count_dataframe.to_excel(writer, sheet_name=sheet_name)
	return xlsx_path


# 获得 l1c zip各个文件大小
def get_l1c_zip_size_xlsx(
		tiles, dates, zip_folder_paths, xlsx_path):
	""""""
	dates = [date.strftime("%Y%m%d") for date in dates]
	zip_count_dataframe = pd.DataFrame(columns=dates, index=tiles)
	for tile in tiles:
		for date in dates:
			zip_file_name_re = f"^S2[AB]_MSIL1C_{date}T.*_T{tile}_.*\.zip$"
			zip_file_sizes = [
				os.path.getsize(os.path.join(zip_folder_path, file_name))
				for zip_folder_path in zip_folder_paths
				for file_name in os.listdir(zip_folder_path)
				if re.match(zip_file_name_re, file_name)
			]
			file_sum = sum(zip_file_sizes)
			if file_sum != 0:
				zip_count_dataframe[date][tile] = file_sum//(1024*1024)
	sheet_name = datetime.datetime.now().strftime('%Y%m%d_%H-%M-%S(MB)')
	if os.path.exists(xlsx_path):
		with pd.ExcelWriter(xlsx_path, mode="a", engine='openpyxl') as writer:
			zip_count_dataframe.to_excel(writer, sheet_name=sheet_name)
	else:
		with pd.ExcelWriter(xlsx_path, mode="w", engine='openpyxl') as writer:
			zip_count_dataframe.to_excel(writer, sheet_name=sheet_name)
	return


# 同步1c的zip文件
def copy_l1c_zips(
		source_folder_path, target_folder_path, tiles=None, dates=None):
	""""""
	tiles = [".*"] if tiles is None else tiles
	if dates is None:
		dates = [".*"]
	else:
		dates = [date.strftime("%Y%m%d") for date in dates]
	target_file_names = [name for name in os.listdir(target_folder_path)]
	source_file_names = [
		name
		for tile in tiles
		for date in dates
		for name in os.listdir(source_folder_path)
		if re.match(f"^S2[AB]_MSIL1C_{date}.*T.*_T{tile}_.*\.zip$", name)
	]
	for source_zip_name in source_file_names:
		source_zip_path = os.path.join(source_folder_path, source_zip_name)
		target_zip_path = os.path.join(target_folder_path, source_zip_name)
		if source_zip_name in target_file_names:
			source_zip_file_size = os.path.getsize(source_zip_path)
			target_zip_file_size = os.path.getsize(target_zip_path)
			if source_zip_file_size != target_zip_file_size:
				print(f"同步：{source_zip_name}")
				shutil.copyfile(source_zip_path, target_zip_path)
		else:
			print(f"同步：{source_zip_name}")
			shutil.copyfile(source_zip_path, target_zip_path)
	return


def main():
	""""""
	'''统计 dir 内的一个省 1c zip count'''
	# province = "河南省"
	start_date, end_date = [2022, 6, 1], [2022, 6, 14]
	zip_folder_paths = [r"H:\新疆"]
	# zip_folder_paths = [r"E:\dataset"]
	xlsx_folder_path = r"E:\\"
	tilestr = r"43SED-43SFD-43SGD-43SFC-43SGC-44SKJ-44SKG-44SLG-44SMG-44SNF-44TLL-44TML-44TNL-44TPL-44TQL-44TLK-44TMK-44TNK-45SUC-45TTF-45TUF-45TVF-45TWF-44SLJ"
	
	# json_path = r"E:\PythonProjcet\RasterShapeToolBox\conf\ChinaMgrs.json"
	# with open(json_path, "r", encoding="utf-8") as json_file:
	# 	china_tiles = json.load(json_file)
	# tiles = china_tiles[province]
	# json_path = r"Z:\冯洋洋\ChinaMgrs.json"
	# tiles = get_tiles(province, json_path=json_path)
	# tilestr = "43SED-43SFD-43SGD-43SFC-43SGC-44SKJ-44SKG-44SLG-44SMG-44SNF-44TLL-44TML-44TNL-44TPL-44TQL-44TLK-44TMK-44TNK-45SUC-45TTF-45TUF-45TVF-45TWF-44SLJ"	
	tiles = tilestr.split("-")
	dates = get_dates(start_date, end_date)
	xlsx_file_name = f"xinjiang_{start_date[0]}-{start_date[1]}.xlsx"
	xlsx_file_path = os.path.join(xlsx_folder_path, xlsx_file_name)
	get_l1c_zip_count_xlsx(tiles, dates, zip_folder_paths, xlsx_file_path)
	'''统计 dir 内的一个省 1c zip size'''
	# province = "山东省"
	# start_date, end_date = [2021, 11, 1], [2021, 12, 1]
	# zip_folder_paths = [r"Z:\A01影像\山东省\2021年\山东省2021rar\11月"]
	# xlsx_folder_path = r"Z:\冯洋洋\temp"
	#
	# json_path = r"Z:\冯洋洋\ChinaMgrs.json"
	# xlsx_file_name = f"Sentinel-2L1cZipDownLoadFileSize.xlsx"
	# tiles = get_tiles(province, json_path=json_path)
	# dates = get_dates(start_date, end_date)
	# xlsx_file_path = os.path.join(xlsx_folder_path, xlsx_file_name)
	# get_l1c_zip_size_xlsx(
	# 	tiles, dates, zip_folder_paths, xlsx_file_path
	# )
	return


if __name__ == "__main__":
	main()
